package com.isoftstone.permissiondemo;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

/**
 * 该类简单修改，适合拷贝修改使用
 */

public class MainActivity extends AppCompatActivity {

    private static final String CALL_PHONE = Manifest.permission.CALL_PHONE;
    public static final String TAG = "MainActivity";
    private static final int REQUEST_PERMISSION_CODE = 100;
    private static final int REQUEST_APP_PERMISSION_SETTING_CODE = 200;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void permission(View view)
    {
        call(CALL_PHONE);
    }

    private void call(String permission) {
        if (checkPermission(permission)) {
//            startActivity(callIntent);
            //TODO 己有权限，按正常逻辑处理
        } else {
            //没有权限，需要申请权限
            startRequestPermision(permission);
        }
    }

    /**
     * 检查是否有权限
     * @param permission
     * @return
     */
    private boolean checkPermission(String permission) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED) {
                //用户设备6.0以上，并且己经赋予了权限
//                Log.e("checkPermission", "PERMISSION_GRANTED" + ContextCompat.checkSelfPermission(this, permission));
                return true;
            } else {
                //用户设备6.0以上，但没有赋予权限
//                Log.e("checkPermission", "PERMISSION_DENIED" + ContextCompat.checkSelfPermission(this, permission));
                return false;
            }
        } else {
            //用户设备6.0以下，直接返回true
//            Log.e("checkPermission", "M以下" + ContextCompat.checkSelfPermission(this, permission));
            return true;
        }
    }

    /**
     * 申请根限
     * @param permission
     */
    private void startRequestPermision(String permission) {
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, REQUEST_PERMISSION_CODE);
    }

    /**
     * 申请权限后的回调
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_PERMISSION_CODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    startActivity(callIntent);
                    // TODO 用户己经授予权限，按正常逻辑处理
                } else {
                    //如果拒绝授予权限,且勾选了再也不提醒
                    if (!shouldShowRequestPermissionRationale(permissions[0])) {
                        Log.d(TAG, "拒绝授予权限,且勾选了再也不提醒 ");
                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        builder.setTitle("说明")
                                .setMessage("需要使用电话权限，进行电话测试")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        showTipGoSetting();
                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.cancel();
                                        return;
                                    }
                                })
                                .create()
                                .show();
                    }
                    //拒绝授予权限，但并未勾选再也不提醒
                    else
                    {
                        Log.d(TAG, "拒绝授予权限，但并未勾选再也不提醒");
                        showTipGoSetting();
                    }
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * 用于在用户勾选“不再提示”并且拒绝时，再次提示用户
     */
    private void showTipGoSetting() {
        new AlertDialog.Builder(this)
                .setTitle("电话权限不可用")
                .setMessage("请在-应用设置-权限-中，允许APP使用电话权限来测试")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用权限设置界面
                        goAppPermissionSetting();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                }).setCancelable(false).show();

    }

    /**
     *跳转到当前应用的权限面，让用户手动授权开启权限
     */
    private void goAppPermissionSetting() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivityForResult(intent, REQUEST_APP_PERMISSION_SETTING_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_APP_PERMISSION_SETTING_CODE)
        {
            //这里的data为空，不清楚怎么回事
            //再次调用该方法如果应用权限开启，可以选择性处理
            call(CALL_PHONE);
        }
    }

}
